import { Table2 } from "../interface/index";

// 获取表数据
export const useTable = (
  initParam: object = {},
  singleCheckAll: boolean,
  selectChange: (params: any[]) => void,
  api?: (params) => Promise<any>,
  dataCallBack?: (data: any) => any
) => {
  const state = reactive<Table2.StateProps>({
    checkAllValue: [],
    tableData: [],
    loading: false,
    multipleIds: [],
    multipleSelection: []
  });

  /**
   * @description 获取表格数据
   * @param {boolean} flag 加载类型
   * @return void
   * */
  const getTableList = async (newApi?: Function) => {
    if (!api) return;
    try {
      state.loading = true;

      // 调用接口获取数据
      let useApi = newApi || api;
      let data = await useApi(initParam);

      // 对返回数据进行修改
      dataCallBack && (data = dataCallBack(data));

      // 获取返回参数
      state.tableData = data ?? [];
      setTimeout(() => {
        state.loading = false;
      }, 500);
    } catch (error) {
      console.log(error);
      state.loading = false;
      state.tableData = [];
    }
  };

  // 是否选中
  const isChecked = (id, className?: "main-multiple") => {
    const name = state.multipleIds.includes(id) ? "multiple-active iconfont icon-xuanze2" : "multiple iconfont icon-xuanze2";
    return name + " " + className;
  };
  // 更多选择
  const setMultipleSelection = (item, row?, rowKey?: number) => {
    const { id } = item;
    const index = state.multipleIds.indexOf(id);

    // 有删除 没有添加
    if (index === -1) {
      state.multipleIds.push(id);
      state.multipleSelection.push(item);
    } else {
      state.multipleIds.splice(index, 1);
      state.multipleSelection.splice(index, 1);
    }

    // 有单个全选 时 单个选择是判断是否勾选全选按钮
    if (singleCheckAll) {
      let count = 0;
      const length = row.value.length;
      for (const item of row.value) {
        if (state.multipleIds.includes(item.id)) {
          count++;
        }
      }
      state.checkAllValue[rowKey] = length === count ? ["全选"] : [];
    }

    selectChange(state.multipleSelection);
  };

  // 单条主数据全选
  const singleGroupChange = (value, index) => {
    state.checkAllValue[index] = value[0];
    const length = state.tableData[index].value.length;
    for (let i = 0; i < length; i++) {
      const item = state.tableData[index].value[i];
      const { id } = item;
      if (value[0]) {
        if (!state.multipleIds.includes(id)) {
          state.multipleIds.push(id);
          state.multipleSelection.push(item);
        }
      } else {
        const delKey = state.multipleIds.indexOf(id);
        if (delKey !== -1) {
          state.multipleIds.splice(delKey, 1);
          state.multipleSelection.splice(delKey, 1);
        }
      }
    }
    selectChange(state.multipleSelection);
  };

  return {
    ...toRefs(state),
    getTableList,
    isChecked,
    setMultipleSelection,
    singleGroupChange
  };
};
